﻿package net.wangit.framework.util;

import java.security.MessageDigest;

import javax.servlet.http.HttpSession;

import net.wangit.context.ActionContext;
import net.wangit.context.ActionContextHelper;
import net.wangit.context.LocalContext;
import net.wangit.framework.session.AgileSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


public class TokenProcessor {

	private static final Log log = LogFactory
			.getLog(net.wangit.framework.util.TokenProcessor.class);

	public TokenProcessor() {
	}

	public static synchronized boolean isTokenValid(ActionContext ac) {
		return isTokenValid(ac, true);
	}

	private static synchronized boolean isTokenValid(ActionContext ac,
			boolean reset) {
		AgileSession session = ActionContextHelper.getSession(ac);
		String key = ac.getRequestParameter(0, "_u_");
		String saved = session.getToken(key);
		if (saved == null)
			return false;
		if (reset)
			session.setToken(key, null);
		String token = ac.getRequestParameter("_t_");
		if (token == null)
			return false;
		else
			return saved.equals(token);
	}

	public static String generateToken(String key) {
		HttpSession httpSession;
		LocalContext lc = LocalContext.getLocalContext();
		httpSession = lc.getHttpServletRequest().getSession();
		String token;
		byte id[] = httpSession.getId().getBytes();
		byte now[] = (new Long(System.currentTimeMillis())).toString()
				.getBytes();
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(id);
			md.update(now);
			token = toHex(md.digest());
			if (token != null) {
				ActionContext ac = LocalContext.getLocalContext()
						.getActionContext();
				AgileSession session = ActionContextHelper.getSession(ac);
				session.setToken(key, token);
			}
			return token;
		} catch (Exception e) {
			log.error(e);
			return null;
		}
	}

	private static String toHex(byte buffer[]) {
		StringBuffer sb = new StringBuffer();
		String s = null;
		for (int i = 0; i < buffer.length; i++) {
			s = Integer.toHexString(buffer[i] & 0xff);
			if (s.length() < 2)
				sb.append('0');
			sb.append(s);
		}

		return sb.toString();
	}

}
